package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.CartPojo;
import com.lei.springbootpractice.service.CartService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/cart")
public class CartController {
    private static final Logger logger = LoggerFactory.getLogger(CartController.class);

    @Autowired
    CartService cartService;

    @GetMapping("/{userId}")
    public Map<String, Object> getCart(@PathVariable String userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<CartPojo> cartItems = cartService.getCartByUserId(userId);
            response.put("success", true);
            response.put("data", cartItems);
        } catch (Exception e) {
            logger.error("获取购物车失败", e);
            response.put("success", false);
            response.put("message", "获取购物车失败: " + e.getMessage());
        }
        return response;
    }

    @PostMapping
    public Map<String, Object> addToCart(HttpSession session, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 参数校验
            if (request == null || !request.containsKey("productId") || !request.containsKey("quantity")) {
                response.put("success", false);
                response.put("message", "参数不完整");
                return response;
            }

            // 获取并验证productId
            String productId = request.get("productId").toString();
            if (productId == null || productId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "商品ID不能为空");
                return response;
            }

            // 获取用户ID
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                response.put("code", 401);
                return response;
            }

            // 创建购物车项
            CartPojo cartItem = new CartPojo();
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            try {
                cartItem.setQuantity(Integer.parseInt(request.get("quantity").toString()));
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "数量必须是整数");
                return response;
            }

            // 调用服务
            boolean result = cartService.addToCart(cartItem);
            response.put("success", result);
            response.put("message", result ? "商品已成功加入购物车" : "操作失败");
            if (result) {
                response.put("data", cartService.getCartByUserId(userId));
            }
        } catch (NumberFormatException e) {
            response.put("success", false);
            response.put("message", "数量必须是整数");
        } catch (RuntimeException e) {
            logger.warn("添加购物车业务异常", e);
            response.put("success", false);
            response.put("message", e.getMessage());
        } catch (Exception e) {
            logger.error("添加购物车系统异常", e);
            response.put("success", false);
            response.put("message", "系统繁忙，请稍后再试");
        }
        return response;
    }

    @DeleteMapping("/{cartId}")
    public Map<String, Object> removeFromCart(@PathVariable String cartId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = cartService.removeFromCart(cartId);
            response.put("success", result);
            response.put("message", result ? "删除成功" : "删除失败");
        } catch (Exception e) {
            logger.error("删除购物车项失败", e);
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
        }
        return response;
    }

    @DeleteMapping("/clear/{userId}")
    public Map<String, Object> clearCart(@PathVariable String userId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = cartService.clearCart(userId);
            response.put("success", result);
            response.put("message", result ? "清空成功" : "清空失败");
        } catch (Exception e) {
            logger.error("清空购物车失败", e);
            response.put("success", false);
            response.put("message", "清空失败: " + e.getMessage());
        }
        return response;
    }

    @DeleteMapping("/remove/{bunchId}")
    public Map<String, Object> removeProductBunch(@PathVariable String bunchId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = cartService.removeProductBunch(bunchId);
            response.put("success", result);
            response.put("message", result ? "删除成功" : "删除失败");
        } catch (Exception e) {
            logger.error("删除商品失败", e);
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
        }
        return response;
    }

    @PostMapping("/update-quantity")
    public Map<String, Object> updateQuantity(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String bunchId = request.get("bunchId").toString();
            int quantity = Integer.parseInt(request.get("quantity").toString());
            boolean result = cartService.updateProductBunchQuantity(bunchId, quantity);
            response.put("success", result);
            response.put("message", result ? "数量更新成功" : "数量更新失败");
        } catch (Exception e) {
            logger.error("更新数量失败", e);
            response.put("success", false);
            response.put("message", "更新数量失败: " + e.getMessage());
        }
        return response;
    }
}
